<template>
  <div class="addArticle">
    <a-row :gutter="5">
      <a-col :span="18">
        <a-row :gutter="10" class="header" v-show="isHidden">
          <a-col :span="20">
            <a-input placeholder="博客标题" v-model="articleTitle" />
          </a-col>
          <a-col :span="4" class="nav">
            <a-select :defaultValue="selectedType" @change="onChange" v-model="selectedType">
              <a-select-option
                v-for="(item, index) in typeInfo"
                :key="index"
                :value="item.id"
              >{{ item.typeName }}</a-select-option>
            </a-select>
          </a-col>
        </a-row>
        <a-row :gutter="10" class="banner">
          <mavon-editor
            ref="md"
            v-model="articleContent"
            :ishljs="true"
            class="markdown-content"
            @imgAdd="$imgAdd"
            @fullScreen="$fullscreen"
          ></mavon-editor>
        </a-row>
      </a-col>
      <a-col :span="6" class="right-col" v-show="isHidden">
        <a-row>
          <a-col :span="24" :gutter="2">
            <a-button>暂存文章</a-button>&nbsp;
            <a-button type="primary" @click="saveArticle">发布文章</a-button>
          </a-col>
          <a-col :span="24" class="main">
            <a-textarea :rows="4" placeholder="文章简介" v-model="introducemd"></a-textarea>
            <br />
            <div class="clearfix upload_img">
              <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
                <div v-if="fileList.length < 1">
                  <a-button>
                    <a-icon type="upload" />Select File
                  </a-button>
                </div>
              </a-upload>
              <img :src="temporaryPath" />
            </div>
          </a-col>
          <a-col :span="12">
            <br />
            <div class="date-select">
              <a-date-picker placeholder="发布日期" @change="setShowDate" v-model="showDate"></a-date-picker>
            </div>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import moment from "moment";
export default {
  created() {
    this.getTypeInfo();
    let id = this.$route.params.id;
    if (id) {
      this.articleId = id;
      this.getArticleById(id);
    }
  },
  data() {
    return {
      articleTitle: "",
      articleContent: "",
      introducemd: "",
      articleId: 0,
      showDate: moment(new Date(), "YYYY-MM-DD"),
      typeInfo: [], //读出所有的后台分类
      selectedType: "请选择类别", //选择的哪一个类别:   （要上传）
      dataString: "",
      isHidden: true,
      fileList: [],
      imgUploadUrl: "",
      temporaryPath: "",
      isUpImg: false,
    };
  },
  methods: {
    // 绑定@imgAdd event
    async $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      let formdata = new FormData();
      formdata.append("image", $file);
      let res = await this.$http({
        url: "/admin/saveUploadImg",
        method: "post",
        data: formdata,
        headers: { "Content-Type": "multipart/form-data" },
      });
      let url = res.data.data.image;
      this.$refs.md.$img2Url(pos, res.data.data.image);
    },
    async getTypeInfo() {
      let res = await this.$http({
        method: "GET",
        url: "/admin/getTypeInfo",
      });
      this.typeInfo = res.data.data;
    },
    onChange(value) {
      this.selectedType = value;
    },
    setShowDate(date, dateString) {
      this.dateString = dateString;
    },
    async saveArticle() {
      if (this.selectedType == "请选择类别") {
        this.$message.error("必须选择文章类型");
        return false;
      } else if (!this.articleTitle) {
        this.$message.error("文章标题不能为空");
        return false;
      } else if (!this.articleContent) {
        this.$message.error("文章内容不能为空");
        return false;
      } else if (!this.introducemd) {
        this.$message.error("文章简介不能为空");
        return false;
      } else if (!this.dateString) {
        this.$message.error("发布日期不能为空");
        return false;
      }
      let dataProps = {};
      dataProps.type_id = this.selectedType;
      dataProps.title = this.articleTitle;
      dataProps.article_content = this.articleContent;
      dataProps.introduce = this.introducemd;
      let dateText = this.dateString.replace("-", "/");
      dataProps.addTime = new Date(dateText).getTime() / 1000;
      if (this.isUpImg) {
        //上传图片
        const { fileList } = this;
        const formData = new FormData();
        fileList.forEach((file) => {
          formData.append("files[]", file);
        });
        let res = await this.$http({
          url: "/admin/saveUploadImg",
          method: "post",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        });
        this.imgUploadUrl = res.data.data["files[]"];
        dataProps.article_url = this.imgUploadUrl;
      }
      if (this.articleId == 0) {
        dataProps.view_count = 0;
        let result = await this.$http({
          method: "POST",
          url: "/admin/addArticle",
          data: dataProps,
        });
        this.articleId = result.data.insertId;
        if (result.data.isSuccess) {
          this.$message.success("文章添加成功");
        } else {
          this.$message.error("文章添加失败");
        }
      } else {
        dataProps.id = this.articleId;
        let res = await this.$http({
          method: "POST",
          url: "/admin/updateArticle",
          data: dataProps,
        });
        if (res.data.isSuccess) {
          this.$message.success("文章保存成功");
        } else {
          this.$message.error("文章保存失败");
        }
      }
    },
    async getArticleById(id) {
      let res = await this.$http.get(`/admin/getArticleById?id=${id}`);
      let articleInfo = res.data.data[0];
      this.articleTitle = articleInfo.title;
      this.articleContent = articleInfo.article_content;
      this.introducemd = articleInfo.introduce;
      this.showDate = moment(articleInfo.addTime, "YYYY-MM-DD");
      this.selectedType = articleInfo.typeId;
      this.temporaryPath = articleInfo.article_url;
    },
    // 切换全屏编辑的回调事件(boolean: 全屏开启状态)
    $fullscreen() {
      this.isHidden = !this.isHidden;
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.temporaryPath = "";
    },
    beforeUpload(file) {
      this.isUpImg = true;
      this.fileList = [...this.fileList, file];
      var reader = new FileReader();
      reader.readAsDataURL(this.fileList[0]);
      reader.onload = (evt) => {
        this.temporaryPath = evt.target.result;
      };
      return false;
    },
  },
};
</script>

<style lang="less">
.right-col {
  padding-left: 15px !important;
}
.aSelect {
  position: relative;
  z-index: 999;
}
.main {
  margin-top: 10px;
}
.markdown-content {
  height: 510px;
}
.header {
  position: relative;
  z-index: 1;
}
.header .nav {
  height: 45px;
}
.banner {
  position: relative;
  z-index: 0;
}
.upload_img {
  width: 100%;
  margin-top: 1rem;
  border: 1px solid #ccc;
  border-radius: 5px;
  img {
    width: 100%;
  }
}
</style>